package com.kadron.dao;

import java.util.Date;

import javax.persistence.EntityManager;
import javax.persistence.NoResultException;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.jboss.seam.annotations.AutoCreate;
import org.jboss.seam.annotations.Name;
import org.jboss.seam.annotations.intercept.BypassInterceptors;

import com.kadron.entity.Discount;

@AutoCreate
@BypassInterceptors
@Name("discountDAO")
public class KDiscountDAO extends KDAO<Discount> {

	private static final Log LOG = LogFactory.getLog(KDiscountDAO.class);
	
	public Discount getKadronDiscount(Date moment) {
		EntityManager em = getEntityManager();
		try {
			return (Discount) em.createQuery("SELECT d FROM Discount d WHERE d.active=TRUE AND d.validFrom <= :moment AND d.validTo >= :moment AND d.type = 0 ORDER BY d.id DESC")
				.setParameter("moment", moment)
				.setMaxResults(1)
				.getSingleResult();			
		} catch (NoResultException e) {
			if (LOG.isDebugEnabled()) {
				LOG.debug("Not found KADRONS Discount");
			}
			return null;
		}
	}
	
}
